from django.conf import settings
from django.shortcuts import render, redirect

from web import models
from web.forms.account import LoginForm


def login(request):
    if request.method == 'GET':
        form = LoginForm()
        return render(request, 'login.html', {"form": form})
    form = LoginForm(data=request.POST)
    if not form.is_valid():
        return render(request, "login.html", {"form": form})
    # 1.接收数据
    data_dict = form.cleaned_data
    # 2.去数据库校验数据
    user_obj = models.Users.objects.filter(active=1).filter(**data_dict).first()

    # 2.1 校验失败
    if not user_obj:
        return render(request, 'login.html', {'form': form, 'error': '用户名或密码错误'})

    # 2.2 校验成功，用户信息写入session
    mapping = {1: "ADMIN", 2: 'MANAGER', 3: 'CUSTOMER'}
    request.session[settings.MOBILEDJ_SESSION_KEY] = {'role': mapping[user_obj.role], 'name': user_obj.username,
                                                      'nickname': user_obj.nickname, 'id': user_obj.id}

    return redirect(settings.LOGIN_HOME)


def sms_login(request):
    return render(request, 'sms_login.html')


def logout(request):
    request.session.clear()
    return redirect(settings.MOBILEDJ_LOGIN_URL)
